/**
 * Created with IntelliJ IDEA.
 * User: 曹长瑞
 * Date: 13-4-15
 * Time: 下午2:13
 */
(function ($) {
    //创建选择对话框
    function create(container) {
        wrap(container);
    }

    //渲染成选择框
    function wrap(jq){
        return jq.each(function(){
            var combo = $(this).after('<span class="searchbox" style="width: '+$(this).css('width')+';height:20px;">' +
                '<input class="searchbox-text" readonly style="width: '+($(this).width()-20)+'px;" />' +
                '<span><span class="searchbox-button" style="height: 20px;line-height: 20px;width: 20px;"></span></span>' +
                '</span>');
            $(this).hide();
            $(this).removeAttr("name");
            if($(this).val()){
                combo.next().find('.searchbox-text').val($(this).val());
            }
            combo.next().find('.searchbox-text').unbind('focus').bind('focus',{target:$(this)},createWindow);
            combo.next().find('.searchbox-button').unbind('click').bind('click',{target:$(this)},createWindow)
                .mouseover(function(){$(this).addClass('searchbox-button-hover')}).mouseout(function(){$(this).removeClass("searchbox-button-hover")});
        });
    }

    //创建对话框
    function createWindow(e){
        var options = $.data(e.data.target[0],'ygSearch').options;
        var dialogDiv = $($("<div id='default-search-dialog' style='padding: 0;'></div>").appendTo('body'));
        dialogDiv.html("<div class='easyui-layout' fit='true'>" +
            "<div region='center'><table class='ygGrid'></table></div>" +
            "<div region='south' style='height: 100px;' split='true'><table></table></div>" +
            "</div><div id='yg-select-toolbar'><div class='textcon'><table class='tb'>" +
            "<tr><th>员工姓名：</th><td><input  type='text' class='input-text' style='width:150px;'/></td>" +
            "<td style='padding-left:5px;'><input type='button' class='submit'/></td></tr></table></div></div>");
        dialogDiv.dialog({
            title:"搜索",
            width:600,
            height:500,
            cache:false,
            buttons: [
                {
                    text: "确定",
                    handler: function(){confirm(e.data.target[0]);}
                },
                {
                    text: "清空",
                    handler: function(){empty(e.data.target[0]);}
                },
                {
                    text: "取消",
                    handler: function () {
                        dialogDiv.dialog("close");
                    }
                }
            ],
            onClose:function(){
                destroy();
            }
        });
        $.data(e.data.target[0],'ygSearch').window = dialogDiv;
        var layout = dialogDiv.find(".easyui-layout").layout();
        if(options.treeUrl){
            layout.layout("add",{
                region: 'west',
                width: 150,
                split: true
            });
            createTree(layout.layout("panel",'west'),e.data.target[0]);
        }
        createDataGrid(layout.layout("panel",'center'),e.data.target[0]);
        createDataGridSelected(layout.layout("panel",'south'),e.data.target[0]);
        $("#yg-select-toolbar input:button").click(function(){search(e.data.target[0])});
    }

    function search(target){
        var options = $.data(target,'ygSearch').options;
        var grid = $.data(target,'ygSearch').grid;
        grid.datagrid("load",{
            xm:$("#yg-select-toolbar input:text").val()
        });
    }

    //选择记录
    function select(target,rowData) {
        return $(target).each(function(){
            var options = $.data(this,'ygSearch').options;
            var gridSelected = $.data(this,'ygSearch').selectedGrid;
            if(options.multiple) {
                if(gridSelected.datagrid("getRowIndex",rowData)==-1)
                    gridSelected.datagrid("appendRow",rowData);
            } else {
                empty(this);
                gridSelected.datagrid("insertRow",{index:0,row:rowData});
            }
            $.data(this,'ygSearch').selectedRecord.push(rowData);
        });
    }
    //确定按钮
    function confirm(target) {
        var selectedRecord = $.data(target,'ygSearch').selectedRecord;
        var opt = $.data(target,'ygSearch').options;
        var window = $.data(target,'ygSearch').window;
        var texts = $.map(selectedRecord,function(v,i){
            return v[opt.textField];
        });
        var name = opt.inputName;
        var input = '';
        for (var i=0;i<selectedRecord.length;i++){
            input += '<input type="hidden" name="'+name+'" value="'+selectedRecord[i][opt.valueField]+'" />';
        }
        $(target).next().find('.searchbox-text').val(texts.join(","));
        $(target).parent().find("input[name='"+name+"']").remove();
        $(target).parent().append($(input));
        $(window).dialog("close");
    }

    //清空选择
    function empty(target) {
        var selectedGrid = $.data(target,'ygSearch').selectedGrid;
        selectedGrid.datagrid("loadData",[]);
        $.data(target,'ygSearch').selectedRecord = [];
    }

    //取消选择
    function cancelSelect() {}

    //销毁对象
    function destroy() {
        $("#default-search-dialog").remove();
    }

    //创建树对象
    function createTree(container,target){
        var options = $.data(target,'ygSearch').options;
        var treeOptions = {
            url:options.treeUrl,
            valueField:'id',
            textField:'text',
            loadFilter:function(rows){
                return convert(rows);
            },
            onSelect:function(node){
                var grid = $.data(target,'ygSearch').grid;
                grid.datagrid("load",{
                    'zgjgId':node.id
                });
            }
        };
        container.wrapInner("<ul />");
        var tree = container.find("ul").tree(treeOptions);
        $.data(target,'ygSearch').tree = tree;
    }

    //创建表格对象
    function createDataGrid(container,target){
        var options = $.data(target,'ygSearch').options;
        var  gridOptions = {
            url:options.gridUrl,
            valueField:options.valueField,
            textField:options.textField,
            idField:options.idField,
            singleSelect:options.multiple,
            toolbar:'#yg-select-toolbar',
            fit:true,
            fitColumns:true,
            pagination:true,
            columns:options.columns,
            onSelect:function(rowIndex, rowData){
                select(target,rowData);
            }
        };
        var grid = container.find("table.ygGrid").datagrid(gridOptions);
        $.data(target,'ygSearch').grid = grid;
    }
    //创建已选表格
    function createDataGridSelected(container,target){
        var options = $.data(target,'ygSearch').options;
        var  gridOptions = {
            //data:[],
            valueField:options.valueField,
            textField:options.textField,
            idField:options.idField,
            fit:true,
            fitColumns:true,
            columns:options.columns
        };
        var grid = container.find("table").datagrid(gridOptions);
        $.data(target,'ygSearch').selectedGrid = grid;
    }

    $.fn.ygSearch = function(options){
        return this.each(function(){
            $.data(this,'ygSearch',{
                options:$.extend({}, $.fn.ygSearch.defaults,options),
                tree:null,
                grid:null,
                selectedGrid:null,
                layout:null,
                window:null,
                selectedRecord:[]
            });
            create($(this));
        });
    }

    $.fn.ygSearch.defaults = {
        treeUrl:null,
        gridUrl:null,
        textField:'xm',
        valueField:'id',
        idField:'id',
        title:'搜索',
        multiple:false,
        inputName:''
    }
})(jQuery);

